package org.smth.search.parser.impl;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.smth.search.parser.ContentParser;
import org.smth.search.parser.PostParser;
import org.smth.search.types.Post;
import org.smth.search.types.PostInfo;
import org.smth.search.types.impl.PostImpl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Singleton
public class PostParserImpl implements PostParser {

	@Inject
	private ContentParser contentParser;

	private Log log = LogFactory.getLog(this.getClass());

	private String reg1 = "^var.*new.*conWriter\\(\\d+,\\s*'(\\w+)',\\s*(\\w+),\\s*(\\d+),\\s*(\\d+),\\s*(\\d+),\\s*'.*',\\s*(\\d+)\\);$";

	//                              boardName       boardid                id           firstId       reId                 num
	private Pattern pattern1 = Pattern.compile(reg1, Pattern.MULTILINE);

	private String reg2 = "^prints\\('(.*)'\\);.*o.h\\(0\\);o.t\\(\\);$";

	// content
	private Pattern pattern2 = Pattern.compile(reg2, Pattern.MULTILINE);

	public Post parsePost(String content) {
		Matcher matcher1 = pattern1.matcher(content);
		Matcher matcher2 = pattern2.matcher(content);
		if (matcher1.find() && matcher2.find()) {
			PostImpl post = new PostImpl();
			post.setBoardName(matcher1.group(1).toLowerCase());
			post.setBoardId(matcher1.group(2));
			post.setId(Integer.parseInt(matcher1.group(3)));
			post.setFirstId(Integer.parseInt(matcher1.group(4)));
			post.setReId(Integer.parseInt(matcher1.group(5)));
			post.setPostNum(Integer.parseInt(matcher1.group(6)));
			content = contentParser.decodeString(matcher2.group(1));
			post.setContent(content);

			PostInfo info = contentParser.parsePostInfo(post, content);
			try {
				BeanUtils.copyProperties(post, info);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return post;
		} else {
			log.warn("正文匹配失败");
			return null;
		}
	}
}
